<?php

namespace frontend\controllers;

use bc\controller\WxOAuthController;
use bc\model\shop\ShopUserModel;
use yii\web\Session;
use bc\model\UserModel;
use bc\model\wc\StaffModel;

class RegstaffController extends WxOAuthController
{
	
	public function init()
	{
		parent::init();
		$session = new Session();
		$user = $session->get('user');
		
		if(!$user)
			$this->redirect('/');
	}
	
	/**
	 * 
	 * @return string
	 */
	public function actionIndex()
	{
		return $this->render ( 'index' );
	}
	
	/**
	 * 保存
	 */
	public function actionSave()
	{
		$msg = [];
		$session = new Session ();
		$user = $session->get ( 'user' );
		$openid = $user ['openid'];
		$ShopUserModel = new ShopUserModel ();
		$shopUser = $ShopUserModel->getRow ( [ 
				'wxid' => $openid 
		] );
		
		$mobile = $this->post ( 'mobile' );
		$real_name = $this->post ( 'real_name' );
		
		if ($shopUser)
		{
			$UserModel = new UserModel ();
			$user = $UserModel->getRow ( [ 
					'wxid' => $openid
			] );
			if (! $user)
			{
				/*
				// 往bc_user插入数据
				$user_id = $UserModel->add ( [ 
						'ecs_user_id' => $shopUser ['user_id'],
						'update_time' => time (),
						'create_time' => time (),
						'wxid' => $openid,
						'mobile' => $mobile,
						'real_name' => $real_name 
				] );
				*/
				if(empty($openid))
					$this->redirect('/booking/index');
				$user_id = $UserModel->saveDate($openid,$mobile,$real_name);
			}
			else
			{
				$data['mobile']=$mobile;
				$data['real_name']=$real_name;
				$data['update_time']=date('Y-m-d H:i:s', time());
				$UserModel->modify($data,$user['id']);
				$user_id = $user ['id'];
			}
			
			// 插入事务表
			$staffModel = new StaffModel ();
			$staff = $staffModel->getRow ( [
					'user_id' => $user_id 
			] );
			if (! $staff)
				$staffModel->add ( [
						'user_id' => $user_id,
						'phone' => $mobile,
						'hospital_id' => 0,
						'update_time' => time (),
						'create_time' => time (),
						'is_invalid' => 1 
				] );
		}
		
		$msg['error'] = 1;
		echo json_encode($msg);
		exit;
	}
}

